//
//  YH_FilesUploadViewController.m
//  YinHang
//
//  Created by apple on 14-9-24.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_FilesUploadViewController.h"
#import "YH_FilelistTableViewCell.h"
#import "YH_AddMoreFileViewController.h"

#import "GetFileUploadList.h"
#import "FileUploadList.h"


@interface YH_FilesUploadViewController ()<UITableViewDataSource,UITableViewDelegate,ASIHTTPRequestDelegate,fileUploadListServiceDelegate>
{
    __weak IBOutlet UITableView *_tableView;

    NSMutableArray *textArray;
    
    NSInteger btnTag;//修改删除链接用
    
    ASIFormDataRequest *delRequest_;//删除请求
    
    GetFileUploadList *fileService;

}

@end

@implementation YH_FilesUploadViewController
- (void)didSaveData:(NSString *)str{

    [textArray addObject:str];
    [_tableView reloadData];

}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"文件列表";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    //设置修改按钮
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-40, 0, 40, 30)];
  
    [rightBtn setTitle:@"添加" forState:UIControlStateNormal];
    [rightBtn setTintColor:[UIColor whiteColor]];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIImage *postBtn_bgImg = [UIImage imageNamed:@"postbtn_bg"];
    [rightBtn setBackgroundImage:[postBtn_bgImg stretchableImageWithLeftCapWidth:postBtn_bgImg.size.width*0.5f topCapHeight:postBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(addMore) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    if (ios7) {
        self.navigationItem.rightBarButtonItems = @[negativeSpacer,rightBarButtonItem];
    }else{
        self.navigationItem.rightBarButtonItems = @[rightBarButtonItem];
    }
    
    //_tableView.rowHeight = 84;
//    if (!IPHONE5) {
//       _tableView.frame=CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height - 152);
//    }
      //tableview委托
    _tableView.dataSource=self;
    _tableView.delegate=self;
    _tableView.rowHeight= 70 ;
    //加长分割线
    if (MAIN_VERSION >= 7) {
        UIEdgeInsets edgeInset = _tableView.separatorInset;
        _tableView.separatorInset = UIEdgeInsetsMake(edgeInset.top, 0, edgeInset.bottom, edgeInset.right);
    }
    
    //隐藏多余分割线
    
    [self setExtraCellLineHidden:_tableView];
    //cell假数据
    textArray=[[NSMutableArray alloc]initWithObjects:@"文件标题一",@"文件标题二",@"文件标题三",nil];
}
-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    //刷新
    [self getDate];
    [self setupRefresh];
    [_tableView headerBeginRefreshing];

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   // return textArray.count;
    if (fileService.pageInfo.dataArr.count != 0) {
        return fileService.pageInfo.dataArr.count;
    }else{
        return 0;
    }

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellId = @"YH_FilelistTableViewCell";
    
    YH_FilelistTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"YH_FilelistTableViewCell" owner:nil options:nil][0];
        
    }
    
    NSUInteger row = [indexPath row];
   
    UIImageView *imageView1 = (UIImageView *)[cell.contentView viewWithTag:1];
    imageView1.image=[UIImage imageNamed:@"item_64"];
     UILabel *label1 = (UILabel *)[cell.contentView viewWithTag:2];
    //label1.text = textArray[row];
    label1.text = fileService.pageInfo.dataArr[row][@"title"];
    UILabel *label2 = (UILabel *)[cell.contentView viewWithTag:3];
    //label2.text=@"文件内容";
    label2.text = fileService.pageInfo.dataArr[row][@"url"];
    
    UIButton *delBtn = (UIButton*)[cell.contentView viewWithTag:5];
    delBtn.tag = row + 5;
    [delBtn addTarget:self action:@selector(delegateFile:) forControlEvents:UIControlEventTouchUpInside];
    

    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [_tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{


    return 70;
}
- (void)setExtraCellLineHidden: (UITableView *)tableView

{
    
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
    
    
}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

    [textArray removeObjectAtIndex:indexPath.row];

    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [_tableView reloadData];
}
//返回

-(void)back{

    [self.navigationController popViewControllerAnimated:YES];

}
//添加文件
-(void)addMore{

    YH_AddMoreFileViewController *YH_amfVC=[[YH_AddMoreFileViewController alloc]initWithNibName:@"YH_AddMoreFileViewController" bundle:nil];
    
    YH_amfVC.delegate=self;
    [self.navigationController pushViewController:YH_amfVC animated:YES];

}
#pragma mark - Custom Method
//获取数据
-(void)getDate{
    fileService = [[GetFileUploadList alloc]init];
    //linkarr = fileService.pageInfo.dataArr;
    fileService.delegate = self;
    
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

-(void)delegateFile:(id)sender{
    UIButton *btn = sender;
    NSLog(@"%i",btn.tag);
    btnTag = btn.tag - 5;
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否删除此条信息？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

#pragma mark - UIAlertViewDelegate
//删除处理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        // 检查网络
        if (![Constants isExistenceNetwork]) {
            
        } else {
            delRequest_ = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
            delRequest_.requestMethod = @"POST";
            // 设置超时时间
            delRequest_.timeOutSeconds = 30;
            delRequest_.delegate = self;
            // 设置参数
            NSString *action = @"uploaddel";
            NSDictionary *paramsDict =  @{@"id":fileService.pageInfo.dataArr[btnTag][@"id"], @"uid": UNAME};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            delRequest_.postBody = [paramsData mutableCopy];
            
            [delRequest_ startAsynchronous];
        }
    }
}

#pragma mark - ASIHTTPRequestDelegate Method

- (void)requestFinished:(ASIHTTPRequest *)request {
    //NSLog(@"%@",request.responseString);
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            //获取选中删除行索引值并通过获取的索引值删除数组中的值
            [fileService.pageInfo.dataArr removeObjectAtIndex:btnTag];
            //删除单元格的某一行时，在用动画效果实现删除过程
            [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:btnTag inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            [_tableView reloadData];
            
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            
        } else {
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}




#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 刷新表格
    [_tableView reloadData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [_tableView headerEndRefreshing];
    // 检查网络
    if (fileService.isQuery || ![Constants isExistenceNetwork]) {
     
     // 刷新表格
     [_tableView reloadData];
     
     // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
     [_tableView headerEndRefreshing];
     
     return;
     }
     
     // 下拉刷新 （请求第一页数据）
     
     // 每次必须重置下 否则会数据混乱
     fileService.pageInfo.pageno = @"1";
     [fileService pageQuery];
}
- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    //    NSLog(@"%i",linkService.isQuery);
    //    NSLog(@"%i",linkService.pageInfo.hasMoreData);
    if (fileService.isQuery || !fileService.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_tableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        fileService.pageInfo.hasMoreData = YES;
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [fileService.pageInfo nextPage];
    [fileService pageQuery];
}
#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}
- (void)didRecieveMsg{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}

-(void)dealloc{
    fileService = nil;
    [delRequest_ cancel];
}
@end